//
//  QuestionnaireViewController.m
//  PigMarket
//
//  Created by 张敬 on 2019/8/13.
//  Copyright © 2019年 pigmarket.oc. All rights reserved.
//

#import "QuestionnaireViewController.h"

#import "QuestionaireHeader.h"
#import "QuestionaireFooter.h"
#import "QuestionaireSectionView.h"

#import "QuestionSectionModel.h"


@interface QuestionnaireViewController ()

@property (nonatomic, strong) QuestionaireHeader *header;
@property (nonatomic, strong) QuestionaireFooter *footer;
@property (nonatomic, strong) QuestionModel *model;
@property (nonatomic, strong) QuestionParam *param;


@end

@implementation QuestionnaireViewController

#pragma mark - lifecycle methods

- (void)setupUI{
    
    {
        self.baseNavView.navTitleLabel.text = @"豚集满意度问卷调查";
        self.baseNavView.navTitleLabel.textColor = KWhiteColor;
        
        [self.baseNavView.leftNavBtn setImage:[UIImage imageNamed:@"nav_white"] forState:UIControlStateNormal];
        
        UIImage *image = [UIImage imageNamed:@"meat_question_nav"];
        self.baseNavView.layer.contents =  (__bridge id)image.CGImage;
    }
}

- (void)setupLayout{
    
    self.reloadBtn.mj_y += 30;
    self.reloadLab.mj_y += 30;
}

#pragma mark - networking methods

- (void)initData{
    
    [self requestQuestionList];
}

- (void)requestQuestionList{
    
    @weakify(self);
    [[[MeatOrderApi sharedInstance] getQuestionList] subscribeNext:^(QuestionModel * _Nullable model) {
        @strongify(self);
        self.model = model;
        
        __block NSMutableArray *aims = [NSMutableArray array];
        [model.list enumerateObjectsUsingBlock:^(QuestionListModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            
            QuestionDataParam *dataParam = [[QuestionDataParam alloc] init];
            [obj.answers enumerateObjectsUsingBlock:^(QuestionAnswersModel * _Nonnull answerModel, NSUInteger index, BOOL * _Nonnull stop) {
            
                if (obj.currentIndex == index) {
                    dataParam.questionnaireId = [NSString stringWithFormat:@"%@", obj.questionnaireId];
                    dataParam.alternativeanswersId = [NSString stringWithFormat:@"%@", answerModel.alternativeanswersId];
                    [aims addObject:dataParam];
                }
            }];
        }];
        
        self.param.data = [aims copy];
        
        if (self.isRefresh) {
            
            [self endRefresh];
        }
        
        if (self.model.list.count >0) {
            self.tableView.hidden = NO;
            [self.tableView reloadData];
        }else{
            [self loadNoData];
        }
        
    }error:^(NSError * _Nullable error) {
        @strongify(self);
        [self loadErrorData];
    }];
}


//下拉刷新
- (void)refresh
{
    [super refresh];
    [self resetData];
    [self initData];
}

- (void)sumibtQuestions{
    
    @weakify(self);
    [self showProgressView];
    [[[MeatOrderApi sharedInstance] applyQuestionsByParams:self.param] subscribeNext:^(NSNull * _Nullable x) {
        @strongify(self);
        [self hideProgressView];
//        double delayInSeconds = 1.5;
//        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
//        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
//            [self.navigationController popViewControllerAnimated:YES];
//        });
        
        [self.navigationController popViewControllerAnimated:YES];

        
    } error:^(NSError * _Nullable error) {
        @strongify(self);
        [self hideProgressView];
        [self showHudWithMsg:@"提交失败"];
    }];
    
}

#pragma mark - tableview.datascource methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.model.list.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    QuestionListModel *listModel = self.model.list[section];
    return listModel.answers.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 75;
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    QuestionaireSectionView *view = [[QuestionaireSectionView alloc] init];
    
    if (section < self.model.list.count) {
        
        QuestionListModel *listModel = self.model.list[section];
        view.titleLab.text = listModel.questionnaireQtitle;
        view.detailLab.text = @"单选";
    }
    
    CAShapeLayer *line = [CAShapeLayer layer];
    line.fillColor = mIconLineColor.CGColor;
    
    UIBezierPath *path = [UIBezierPath bezierPathWithRect:CGRectMake(0, 74.5, KScreenWidth, 0.5)];
    line.path = path.CGPath;
    [view.layer addSublayer:line];

    return  view;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"QSCollectionCell" forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    if (indexPath.section < self.model.list.count) {
        QuestionListModel *listModel = self.model.list[indexPath.section];
        if (indexPath.row < listModel.answers.count) {
            
            cell.imageView.image = listModel.currentIndex == indexPath.row
            ?[UIImage imageNamed:@"meat_complaints_selected"]
            :[UIImage imageNamed:@"meat_complaints_unselected"];
            
            QuestionAnswersModel *answersModel = listModel.answers[indexPath.row];
            cell.textLabel.text = answersModel.alternativeanswersTitle;
            cell.textLabel.textColor = UIColorFromRGB(0x666666);
            cell.textLabel.font = mFont(15);
        }
    }

    return cell;
}

#pragma mark - tableview.delegate methods

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    if (indexPath.section < self.model.list.count) {
        
        QuestionListModel *listModel = self.model.list[indexPath.section];
        listModel.currentIndex = indexPath.row;
        [self localReloadTableViewBySection:indexPath.section];
    }
}

#pragma mark - getter methods

- (QuestionaireHeader *)header
{
    if (!_header) {
        _header = [[QuestionaireHeader alloc] init];
    }
    return _header;
}

- (QuestionaireFooter *)footer
{
    if (!_footer) {
        _footer = [[QuestionaireFooter alloc] init];
        
        @weakify(self);
        _footer.dealSumbitBlock = ^{
            @strongify(self);
            [self sumibtQuestions];
        };
    }
    return _footer;
}


- (QuestionModel *)model{
    
    if (!_model) {
        _model = [[QuestionModel alloc] init];
    }
    return _model;
}

- (QuestionParam *)param{
    
    if (!_param) {
        _param = [[QuestionParam alloc] init];
        _param.memberId = kMemberId;
        
    }
    return _param;
}

#pragma mark - override methods

- (void)registerTableViewCell
{
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"QSCollectionCell"];
    self.tableView.rowHeight = 50;
    self.tableView.height = KScreenHeight - TJ_NavBarHeight;
    self.tableView.mj_y = TJ_NavBarHeight;
    self.tableView.tableHeaderView = self.header;
    self.tableView.tableFooterView = self.footer;
    self.tableView.mj_footer.hidden = YES;
    self.tableView.mj_header.hidden = YES;
    
    self.tableView.separatorColor = mIconLineColor;
}

- (void)loadErrorData
{
    [super loadErrorData];
    self.footer.hidden = YES;
    self.header.hidden = YES;
}

- (void)loadNoData
{
    [super loadNoData];
    self.footer.hidden = YES;
    self.header.hidden = YES;
}


- (void)endLoadMore{
    [super endLoadMore];
    self.footer.hidden = YES;
    self.header.hidden = YES;
}

- (void)endRefresh{
    [super endRefresh];
    self.footer.hidden = NO;
    self.header.hidden = NO;
}

- (void)endLoadMoreMoData
{
    [super endLoadMoreMoData];
    self.footer.hidden = NO;
    self.header.hidden = NO;
}


@end
